import { ajax } from "./utils/ajax"

const shaderSplice = "<#BREAK_BN#>";

/**
 * 从url同时加载顶点和片元着色器
 * @param {WebGL对象} gl 
 * @param {shader代码地址} url 
 */
function loadShaderFromUrl(gl, url, callback){
    ajax(url, {}, function(){
        //console.log(gl)
        var shaderStr = arguments[0];
        var shaders = shaderStr.split(shaderSplice);
        if(shaders.length < 2){
            throw new Error("着色器代码不完整!");
        }
        var vertexShader = gl.createShader(gl.VERTEX_SHADER);
        gl.shaderSource(vertexShader, shaders[0]);
        gl.compileShader(vertexShader);
        if(!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)){
            throw new Error("编译顶点着色器失败!");
        }
        gl.vertexShader = vertexShader;

        var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
        gl.shaderSource(fragmentShader, shaders[1]);
        gl.compileShader(fragmentShader);
        if(!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)){
            throw new Error("编译片元着色器失败!");
        }
        gl.fragmentShader = fragmentShader;

        callback();
    });
}

/**
 * 从DOM加载单个着色器
 * @param {WebGL对象} gl 
 * @param {着色器DOM元素id} id 
 */
function loadShaderFromDom(gl,id){
    var shaderScript = document.getElementById(id);
    if(!shaderScript){
        throw new Error("不存在"+id+"元素!");
        return null;
    }

    var shader;
    var shaderType;
    if(shaderScript.type === "x-shader/x-vertex"){
        shader = gl.createShader(gl.VERTEX_SHADER);
        shaderType = "vertexShader";
    }else if(shaderScript.type === "x-shader/x-fragment"){
        shader = gl.createShader(gl.FRAGMENT_SHADER); 
        shaderType = "fragmentShader";
    }else{
        throw new Error("着色器DOM为空!");
        return null;
    }

    var shaderSource = shaderScript.innerText;
    gl.shaderSource(shader, shaderSource);
    gl.compileShader(shader);
    if(!gl.getShaderParameter(shader, gl.COMPILE_STATUS)){
        throw new Error("加载着色器失败!");
        return null;
    }
    gl[shaderType] = shader;
    return shader;
}

export { loadShaderFromDom, loadShaderFromUrl };